"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  ArrowLeft,
  Bell,
  Search,
  Filter,
  Check,
  Bookmark,
  Trash2,
  Settings,
  Users,
  MessageSquare,
  Calendar,
  DollarSign,
  AlertCircle,
  Heart,
  Clock,
} from "lucide-react"

export default function NotificationsPage() {
  const router = useRouter()
  const [activeTab, setActiveTab] = useState("all")
  const [searchQuery, setSearchQuery] = useState("")
  const [currentUser, setCurrentUser] = useState<any>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [notifications, setNotifications] = useState([])

  // 默认通知数据
  const defaultNotifications = [
    {
      id: 1,
      type: "system",
      title: "系统维护通知",
      content: "系统将于今晚23:00-01:00进行维护升级，期间可能影响部分功能使用。",
      time: "2小时前",
      read: false,
      important: true,
      bookmarked: false,
      sender: "系统管理员",
      avatar: "/placeholder.svg?height=32&width=32",
    },
    {
      id: 2,
      type: "social",
      title: "张创业 点赞了你的动态",
      content: "你发布的《创业路上的那些坑》获得了张创业的点赞。",
      time: "4小时前",
      read: false,
      important: false,
      bookmarked: true,
      sender: "张创业",
      avatar: "/placeholder.svg?height=32&width=32",
    },
    {
      id: 3,
      type: "business",
      title: "新的专家咨询预约",
      content: "李导师已确认你的咨询预约，时间：明天下午2:00-3:00。",
      time: "6小时前",
      read: true,
      important: true,
      bookmarked: false,
      sender: "专家咨询系统",
      avatar: "/placeholder.svg?height=32&width=32",
    },
    {
      id: 4,
      type: "event",
      title: "活动提醒：创业者聚会",
      content: "你报名的「创业者线下聚会」将于今晚7点开始，地点：上海市浦东新区。",
      time: "8小时前",
      read: true,
      important: false,
      bookmarked: false,
      sender: "活动组织者",
      avatar: "/placeholder.svg?height=32&width=32",
    },
    {
      id: 5,
      type: "funding",
      title: "融资机会推荐",
      content: "根据你的项目特点，为你推荐了3个匹配的投资机构。",
      time: "1天前",
      read: true,
      important: false,
      bookmarked: true,
      sender: "融资助手",
      avatar: "/placeholder.svg?height=32&width=32",
    },
    {
      id: 6,
      type: "community",
      title: "社区新消息",
      content: "「AI创业交流群」有5条新消息，快去看看大家在讨论什么吧！",
      time: "1天前",
      read: true,
      important: false,
      bookmarked: false,
      sender: "社区管理员",
      avatar: "/placeholder.svg?height=32&width=32",
    },
  ]

  const getNotificationIcon = (type) => {
    switch (type) {
      case "system":
        return <Settings className="w-4 h-4" />
      case "social":
        return <Heart className="w-4 h-4" />
      case "business":
        return <Users className="w-4 h-4" />
      case "event":
        return <Calendar className="w-4 h-4" />
      case "funding":
        return <DollarSign className="w-4 h-4" />
      case "community":
        return <MessageSquare className="w-4 h-4" />
      default:
        return <Bell className="w-4 h-4" />
    }
  }

  const getNotificationColor = (type) => {
    switch (type) {
      case "system":
        return "bg-blue-100 text-blue-600"
      case "social":
        return "bg-pink-100 text-pink-600"
      case "business":
        return "bg-green-100 text-green-600"
      case "event":
        return "bg-purple-100 text-purple-600"
      case "funding":
        return "bg-yellow-100 text-yellow-600"
      case "community":
        return "bg-orange-100 text-orange-600"
      default:
        return "bg-slate-100 text-slate-600"
    }
  }

  // 检查用户登录状态并加载通知
  useEffect(() => {
    const user = localStorage.getItem('currentUser')
    if (!user) {
      alert('请先登录后使用此功能')
      router.push('/login')
      return
    }
    const userData = JSON.parse(user)
    setCurrentUser(userData)
    
    // 加载用户通知，优先使用保存的通知，否则使用默认通知
    const savedNotifications = localStorage.getItem(`notifications_${userData.id}`)
    if (savedNotifications) {
      setNotifications(JSON.parse(savedNotifications))
    } else {
      setNotifications(defaultNotifications)
      // 保存默认通知
      localStorage.setItem(`notifications_${userData.id}`, JSON.stringify(defaultNotifications))
    }
    setIsLoading(false)
  }, [router])

  // 保存通知状态到localStorage
  const saveNotifications = (updatedNotifications: any[]) => {
    if (currentUser) {
      localStorage.setItem(`notifications_${currentUser.id}`, JSON.stringify(updatedNotifications))
    }
  }

  const handleMarkAsRead = (id: number) => {
    const updatedNotifications = notifications.map((notif: any) => 
      notif.id === id ? { ...notif, read: true } : notif
    )
    setNotifications(updatedNotifications)
    saveNotifications(updatedNotifications)
  }

  const handleMarkAllAsRead = () => {
    const updatedNotifications = notifications.map((notif: any) => ({ ...notif, read: true }))
    setNotifications(updatedNotifications)
    saveNotifications(updatedNotifications)
  }

  const handleBookmark = (id: number) => {
    const updatedNotifications = notifications.map((notif: any) => 
      notif.id === id ? { ...notif, bookmarked: !notif.bookmarked } : notif
    )
    setNotifications(updatedNotifications)
    saveNotifications(updatedNotifications)
  }

  const handleDelete = (id: number) => {
    const updatedNotifications = notifications.filter((notif: any) => notif.id !== id)
    setNotifications(updatedNotifications)
    saveNotifications(updatedNotifications)
  }

  const filteredNotifications = notifications.filter((notif: any) => {
    if (activeTab === "unread" && notif.read) return false
    if (activeTab === "bookmarked" && !notif.bookmarked) return false
    if (activeTab === "important" && !notif.important) return false
    if (
      searchQuery &&
      !notif.title.toLowerCase().includes(searchQuery.toLowerCase()) &&
      !notif.content.toLowerCase().includes(searchQuery.toLowerCase())
    )
      return false
    return true
  })

  const unreadCount = notifications.filter((n: any) => !n.read).length

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-4 border-slate-300 border-t-slate-600 rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-slate-600">加载通知...</p>
        </div>
      </div>
    )
  }

  if (!currentUser) {
    return null
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50/30 to-purple-50/30">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-xl border-b border-slate-200/50 sticky top-0 z-50">
        <div className="max-w-4xl mx-auto px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button variant="ghost" onClick={() => router.back()}>
                <ArrowLeft className="w-4 h-4 mr-2" />
                返回
              </Button>
              <div className="flex items-center space-x-2">
                <Bell className="w-6 h-6 text-blue-600" />
                <h1 className="text-xl font-semibold text-slate-900">通知中心</h1>
                {unreadCount > 0 && <Badge className="bg-red-100 text-red-700">{unreadCount} 条未读</Badge>}
              </div>
            </div>
            <Button onClick={handleMarkAllAsRead} disabled={unreadCount === 0}>
              <Check className="w-4 h-4 mr-2" />
              全部已读
            </Button>
          </div>
        </div>
      </header>

      <main className="max-w-4xl mx-auto px-6 py-8">
        <div className="space-y-6">
          {/* 搜索和筛选 */}
          <div className="flex space-x-4">
            <div className="relative flex-1">
              <Search className="w-4 h-4 absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" />
              <Input
                placeholder="搜索通知..."
                className="pl-10"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
            <Button variant="outline">
              <Filter className="w-4 h-4 mr-2" />
              筛选
            </Button>
          </div>

          {/* 标签页 */}
          <Tabs value={activeTab} onValueChange={setActiveTab}>
            <TabsList className="grid w-full grid-cols-4">
              <TabsTrigger value="all">全部 ({notifications.length})</TabsTrigger>
              <TabsTrigger value="unread">未读 ({unreadCount})</TabsTrigger>
              <TabsTrigger value="bookmarked">收藏 ({notifications.filter((n) => n.bookmarked).length})</TabsTrigger>
              <TabsTrigger value="important">重要 ({notifications.filter((n) => n.important).length})</TabsTrigger>
            </TabsList>

            <TabsContent value={activeTab} className="mt-6">
              {filteredNotifications.length === 0 ? (
                <Card>
                  <CardContent className="p-12 text-center">
                    <Bell className="w-12 h-12 text-slate-400 mx-auto mb-4" />
                    <h3 className="text-lg font-medium text-slate-900 mb-2">暂无通知</h3>
                    <p className="text-slate-600">
                      {activeTab === "unread" && "所有通知都已阅读"}
                      {activeTab === "bookmarked" && "还没有收藏的通知"}
                      {activeTab === "important" && "暂无重要通知"}
                      {activeTab === "all" && "暂时没有任何通知"}
                    </p>
                  </CardContent>
                </Card>
              ) : (
                <div className="space-y-3">
                  {filteredNotifications.map((notification) => (
                    <Card
                      key={notification.id}
                      className={`transition-all duration-200 hover:shadow-md ${
                        !notification.read ? "bg-blue-50/50 border-blue-200" : "bg-white/70"
                      }`}
                    >
                      <CardContent className="p-6">
                        <div className="flex items-start space-x-4">
                          <Avatar className="w-10 h-10">
                            <AvatarImage src={notification.avatar || "/placeholder.svg"} />
                            <AvatarFallback>{notification.sender[0]}</AvatarFallback>
                          </Avatar>

                          <div className="flex-1 min-w-0">
                            <div className="flex items-center space-x-2 mb-2">
                              <div className={`p-1 rounded-full ${getNotificationColor(notification.type)}`}>
                                {getNotificationIcon(notification.type)}
                              </div>
                              <h3 className={`font-medium ${!notification.read ? "text-slate-900" : "text-slate-700"}`}>
                                {notification.title}
                              </h3>
                              {notification.important && (
                                <Badge className="bg-red-100 text-red-700">
                                  <AlertCircle className="w-3 h-3 mr-1" />
                                  重要
                                </Badge>
                              )}
                              {!notification.read && <div className="w-2 h-2 bg-blue-600 rounded-full"></div>}
                            </div>

                            <p className="text-slate-600 text-sm mb-3 leading-relaxed">{notification.content}</p>

                            <div className="flex items-center justify-between">
                              <div className="flex items-center space-x-4 text-xs text-slate-500">
                                <div className="flex items-center space-x-1">
                                  <Clock className="w-3 h-3" />
                                  <span>{notification.time}</span>
                                </div>
                                <span>来自 {notification.sender}</span>
                              </div>

                              <div className="flex items-center space-x-2">
                                {!notification.read && (
                                  <Button variant="ghost" size="sm" onClick={() => handleMarkAsRead(notification.id)}>
                                    <Check className="w-3 h-3" />
                                  </Button>
                                )}
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleBookmark(notification.id)}
                                  className={notification.bookmarked ? "text-yellow-600" : ""}
                                >
                                  <Bookmark className={`w-3 h-3 ${notification.bookmarked ? "fill-current" : ""}`} />
                                </Button>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  onClick={() => handleDelete(notification.id)}
                                  className="text-red-600 hover:text-red-700"
                                >
                                  <Trash2 className="w-3 h-3" />
                                </Button>
                              </div>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              )}
            </TabsContent>
          </Tabs>
        </div>
      </main>
    </div>
  )
}
